package com.learn.concurrent;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author wangxing
 * @version 2020/9/4 11:44 Administrator
 */
public class LearnScheduledExecutor {
    public static final Logger logger = LoggerFactory.getLogger(LearnScheduledExecutor.class);
    public static final ScheduledThreadPoolExecutor threadPoolExecutor = new ScheduledThreadPoolExecutor(10);
    public static void main(String[] args) {
//        周期性执行，每5秒执行一次
        periodicTimeOutRunThread(5);
//        periodicRunThread(5);
//        delayRunThread(5);
        try {
            TimeUnit.SECONDS.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        threadPoolExecutor.shutdown();
    }

    /**
     * 周期性运行一个程序
     * @param periodNum 运行周期事件间隔秒
     */
    public static void periodicRunThread(Integer periodNum){
        threadPoolExecutor.scheduleAtFixedRate(()->{
            logger.info("Periodic execution run thread ,run time is {}-----------------", LocalDateTime.now());
        },0,periodNum, TimeUnit.SECONDS);
    }

    /**
     * 超时运行周期性时间间隔线程
     * 每次执行周期是在上一个线程执行完后就执行下一个线程
     * @param periodNum 运行周期事件间隔秒
     */
    public static void periodicTimeOutRunThread(Integer periodNum){
        threadPoolExecutor.scheduleAtFixedRate(()->{
            try {
                TimeUnit.SECONDS.sleep(periodNum+1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            logger.info("Periodic execution run thread ,run time is {}-----------------", LocalDateTime.now());
        },0,periodNum, TimeUnit.SECONDS);
    }
    /**
     * 延迟指定时间后执行
     * @param secondNum 延迟描述
     */
    public static void delayRunThread(Integer secondNum ){
        //        延迟secondNum秒后执行
        logger.info("runtime start is {} ",LocalDateTime.now());
        threadPoolExecutor.schedule(()->{
            logger.info("---------------------delay Thread start,run time is {}", LocalDateTime.now());
        },secondNum, TimeUnit.SECONDS);
    }
}
